package com.gujiangbo.multithreadskill;

import java.util.Date;

/**
 * @author gujiangbo
 * @description Suspend() 方法暂停线程，不释放锁，导致数据不一致
 * resume() 方法恢复线程的执行
 * @date 2020/10/24
 */
public class Suspend_and_resume {

    public static void main(String[] args) throws Exception {
        SuThread thread = new SuThread();
        thread.start();
        Thread.sleep(5000);
        // A 段 暂停线程执行
        thread.suspend();
        System.out.println("A = " + System.currentTimeMillis() + " i=" + thread.getI());
        Thread.sleep(5000);
        System.out.println("A = " + System.currentTimeMillis() + " i=" + thread.getI());

        //B 段 恢复线程执行
        thread.resume();
        Thread.sleep(5000);

        //C 段 暂停线程执行
        thread.suspend();
        System.out.println("B = " + System.currentTimeMillis() + " i=" + thread.getI());
        Thread.sleep(5000);
        System.out.println("B = " + System.currentTimeMillis() + " i=" + thread.getI());

        // D 恢复线程执行后，在结束线程执行
        thread.resume();
        thread.interrupt();
        System.out.println("D =" + new Date(System.currentTimeMillis()) + " i=" + thread.getI());

    }
}

class SuThread extends Thread {
    private long i = 0;

    public long getI() {
        return i;
    }

    public void setI(long i) {
        this.i = i;
    }

    @Override
    public void run() {
        while (true) {
            i++;
            if (this.isInterrupted()) {
                System.out.println("线程结束.");
                return;
            }
        }
    }
}